package ilender.util;

import java.util.regex.Pattern;

/**
 * Tools for converting stuff.
 */
public final class ConversionTools{
	/*Instantiation Guard*/private ConversionTools(){}

	private static Pattern apostrophePattern=null;

	/**Converts a Java object to be written in a PostgreSQL query or statement.*/
	public static String toPostgresqlLiteral(Object source){
		if(source instanceof String){
			String result=(String)source;
			if(null==apostrophePattern)
				apostrophePattern=Pattern.compile("'");
			result=apostrophePattern.matcher(result).replaceAll("''");
			return String.format("'%s'",result);
		}else if(source instanceof Iterable){
			boolean isFirst=true;
			StringBuilder result=new StringBuilder();
			result.append('{');
			for(Object entry:(Iterable)source){
				if(isFirst)
					isFirst=false;
				else
					result.append(',');
				result.append(toPostgresqlLiteral(entry));
			}
			result.append('}');
			return result.toString();
		}
		return source.toString();
	}
}
